package com.wish233.register.impl;

import com.wish233.model.register.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册中心服务本地缓存
 *
 * @author WHH
 */
public class RegistryServiceCache {

    /**
     * 服务缓存
     */
    private static final Map<String, List<ServiceMetaInfo>> SERVICE_CACHE = new ConcurrentHashMap<>();

    private static volatile RegistryServiceCache instance;

    /**
     * 双检锁单例
     *
     * @return
     */
    static RegistryServiceCache getCache() {
        if (instance == null) {
            synchronized (RegistryServiceCache.class) {
                if (instance == null) {
                    instance = new RegistryServiceCache();
                }
            }
        }
        return instance;
    }

    /**
     * 写缓存
     *
     * @param newServiceCache
     * @return
     */
    void writeCache(String serviceKey, List<ServiceMetaInfo> newServiceCache) {
        SERVICE_CACHE.put(serviceKey, newServiceCache);
    }

    /**
     * 读缓存
     *
     * @return
     */
    List<ServiceMetaInfo> readCache(String serviceKey) {
        return SERVICE_CACHE.get(serviceKey);
    }

    /**
     * 清空缓存
     */
    void clearCache(String serviceKey) {
        SERVICE_CACHE.remove(serviceKey);
    }

    /**
     * 清空缓存
     */
    void clearAll() {
        SERVICE_CACHE.clear();
    }
}
